<!DOCTYPE html>
<html lang="en">
<head>
    <!-- 保持原有head内容不变 -->
</head>
<body>
    <!-- 保持原有DOM结构不变 -->

    <script>
        // DOM元素
        const localVideo = document.getElementById('localVideo');
        const remoteVideo = document.getElementById('remoteVideo');
        const toggleAudioBtn = document.getElementById('toggleAudio');
        const toggleVideoBtn = document.getElementById('toggleVideo');

        // WebRTC状态变量
        let localStream;
        let peerConnection;
        let audioEnabled = true;
        let videoEnabled = true;
        let ws;

        // ==================== 新增：状态跟踪 ====================
        const connectionState = {
            hasLocalOffer: false,
            hasRemoteAnswer: false,
            isSettingRemote: false
        };

        // ==================== 初始化函数 ====================
        function init() {
            cleanup(); // 先清理旧资源
            setupWebSocket();
            startMedia();
        }

        // ==================== 清理函数（关键！） ====================
        function cleanup() {
            console.log('Cleaning up resources...');
            
            // 关闭PeerConnection
            if (peerConnection) {
                peerConnection.ontrack = null;
                peerConnection.onicecandidate = null;
                peerConnection.onnegotiationneeded = null;
                peerConnection.close();
                peerConnection = null;
            }
            
            // 关闭媒体流
            if (localStream) {
                localStream.getTracks().forEach(track => track.stop());
                localVideo.srcObject = null;
                localStream = null;
            }
            
            // 关闭WebSocket
            if (ws) {
                ws.onmessage = null;
                ws.onclose = null;
                ws.close();
                ws = null;
            }
            
            // 重置视频元素
            remoteVideo.srcObject = null;
            
            // 重置状态
            connectionState.hasLocalOffer = false;
            connectionState.hasRemoteAnswer = false;
            connectionState.isSettingRemote = false;
        }

        // ==================== WebSocket设置 ====================
        function setupWebSocket() {
            ws = new WebSocket('wss://192.168.0.120:8888');
            
            ws.onopen = () => {
                console.log('WebSocket connected');
                ws.send(JSON.stringify({ type: 'register-pc' }));
            };
            
            ws.onmessage = async (message) => {
                try {
                    const data = JSON.parse(message.data);
                    console.log('PC received:', data.type);

                    if (data.type === 'answer') {
                        await safeSetRemoteDescription(data.answer);
                    } 
                    else if (data.type === 'candidate') {
                        await safeAddIceCandidate(data.candidate);
                    }
                } catch (error) {
                    console.error('Error processing message:', error);
                }
            };
            
            ws.onerror = (error) => {
                console.error('WebSocket error:', error);
            };
            
            ws.onclose = () => {
                console.log('WebSocket disconnected');
            };
            
            // 页面关闭前清理
            window.addEventListener('beforeunload', cleanup);
            window.addEventListener('pagehide', cleanup);
        }

        // ==================== 安全的远程描述设置 ====================
        async function safeSetRemoteDescription(answer) {
            if (connectionState.isSettingRemote) {
                console.warn('Already setting remote description');
                return;
            }
            
            if (!peerConnection) {
                console.error('No peerConnection when setting answer');
                return;
            }

            connectionState.isSettingRemote = true;
            
            try {
                await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
                connectionState.hasRemoteAnswer = true;
                console.log('Successfully set remote answer');
            } catch (error) {
                console.error('Failed to set remote description:', error);
                
                // 如果是状态错误，尝试恢复
                if (error.toString().includes('wrong state: stable')) {
                    console.log('Attempting to recover...');
                    await restartConnection();
                }
            } finally {
                connectionState.isSettingRemote = false;
            }
        }

        // ==================== 安全的候选添加 ====================
        async function safeAddIceCandidate(candidate) {
            if (!peerConnection || !connectionState.hasLocalOffer) {
                console.warn('Not ready to add ICE candidate');
                return;
            }
            
            try {
                await peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
                console.log('Successfully added ICE candidate');
            } catch (error) {
                console.error('Failed to add ICE candidate:', error);
            }
        }

        // ==================== 重启连接 ====================
        async function restartConnection() {
            console.log('Restarting connection...');
            cleanup();
            await startMedia();
        }

        // ==================== 初始化PeerConnection ====================
        function createPeerConnection() {
            console.log('Creating new PeerConnection');
            peerConnection = new RTCPeerConnection({
                iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
            });

            peerConnection.ontrack = (event) => {
                console.log('Received track:', event.track.kind);
                if (event.streams && event.streams[0]) {
                    remoteVideo.srcObject = event.streams[0];
                }
            };

            peerConnection.onicecandidate = (event) => {
                if (event.candidate) {
                    ws.send(JSON.stringify({ 
                        type: 'candidate', 
                        candidate: event.candidate 
                    }));
                }
            };

            if (localStream) {
                localStream.getTracks().forEach(track => {
                    peerConnection.addTrack(track, localStream);
                });
            }
        }

        // ==================== 启动媒体和信令 ====================
        async function startMedia() {
            try {
                console.log('Starting media...');
                const constraints = {
                    audio: true,
                    video: { width: { ideal: 1280 }, height: { ideal: 720 } }
                };
                
                localStream = await navigator.mediaDevices.getUserMedia(constraints);
                localVideo.srcObject = localStream;
                
                createPeerConnection();
                
                // 创建并发送offer
                const offer = await peerConnection.createOffer();
                await peerConnection.setLocalDescription(offer);
                connectionState.hasLocalOffer = true;
                
                ws.send(JSON.stringify({ type: 'offer', offer }));
                console.log('Offer sent');
            } catch (error) {
                console.error('Error starting media:', error);
                setTimeout(restartConnection, 1000); // 1秒后重试
            }
        }

        // ==================== 控制按钮事件 ====================
        toggleAudioBtn.addEventListener('click', () => {
            audioEnabled = !audioEnabled;
            if (localStream) {
                localStream.getAudioTracks().forEach(track => {
                    track.enabled = audioEnabled;
                });
            }
            toggleAudioBtn.textContent = audioEnabled ? '关闭麦克风' : '开启麦克风';
        });

        toggleVideoBtn.addEventListener('click', () => {
            videoEnabled = !videoEnabled;
            if (localStream) {
                localStream.getVideoTracks().forEach(track => {
                    track.enabled = videoEnabled;
                });
            }
            toggleVideoBtn.textContent = videoEnabled ? '关闭摄像头' : '开启摄像头';
        });

        // 初始化应用
        init();
    </script>
</body>
</html>